package work.xiaohong.arithmetic.IO;

import lombok.Cleanup;

import java.io.*;

/**
 * @author xiaohong
 * @version 1.0
 * @date 2021/10/27 0027 11:40
 * @description 缓冲字节流
 * 提高io效率，减少磁盘访问次数 数据存储在缓冲区中，flush将缓冲区内容刷入文件中，close也会触发flush
 * @Cleanup 是Lombok注解，会帮我们关闭流
 */
public class BufferedStream {

    public static void main(String[] args) throws Exception {
//        writeFile();
//        readFile();
        copyFile();
    }

    // 写入文件
    public static void writeFile() throws Exception {
        // 后面的参数表示是否要子在原来的内容后面追加新内容
        FileOutputStream fileOutputStream = new FileOutputStream("a.txt",true);
        @Cleanup
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);

        for (int i = 100; i > 0; i--) {
            bufferedOutputStream.write(String.valueOf(i+"\n").getBytes());
            // 不要等close的flush，如果中途断电了，会造成数据丢失
            bufferedOutputStream.flush();
        }
        // 关闭流的时候会自动flush()
//        bufferedOutputStream.close();
    }


    // 读取文件
    public static void readFile() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
        // 内置缓存区 默认是8k
        @Cleanup
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        int data = 0;
        while ((data = bufferedInputStream.read()) != -1){
            System.out.println((char) data);
        }
    }


    // 复制文件
    public static void copyFile() throws Exception {
        FileInputStream fileInputStream = new FileInputStream("a.txt");
        @Cleanup
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        FileOutputStream fileOutputStream = new FileOutputStream("b.txt",true);
        @Cleanup
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        int data = 0;
        while ((data = bufferedInputStream.read()) != -1){
            bufferedOutputStream.write(data);
            bufferedOutputStream.flush();
        }
    }

}
